package com.mingtu.guards.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.FileAdapter;
import com.mingtu.guards.bean.ExchangeMessageBean;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class FileFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.empty_layout)
    EmptyDataLayout emptyLayout;

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private int id;
    private static final String ARG_PARAM = "param";
    private FileAdapter fileAdapter;
    private List<ExchangeMessageBean.PageBean.ListBean> DataBean = new ArrayList<>();
    private List<String> data = new ArrayList<>();

    public static FileFragment getInstance(int id) {
        FileFragment ef = new FileFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_PARAM, id);
        ef.setArguments(bundle);
        return ef;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getInt(ARG_PARAM);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_file;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView(View view) {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new SpacesItemDecoration(0, 0, 0, 15, 15));
        //添加自定义分割线
//        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
//        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_dive_line));
//        recycler.addItemDecoration(divider);


        fileAdapter = new FileAdapter(context, DataBean);
        recycler.setAdapter(fileAdapter);
        fileAdapter.setOnItemClickListener(new FileAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                String id = DataBean.get(position).getId() + "";
//                Bundle bundle = new Bundle();
//                bundle.putString("id", id);
//                IntentUtils.getInstance().readyGo(getActivity(), NewsDetailsActivity.class, bundle);
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
//        getNewList(1);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            File[] files = getActivity().getExternalFilesDirs(Environment.MEDIA_MOUNTED);
            getFileInfo(files);
        }
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
//                getNewList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(DataBean, Constant.PAGE_SIZE);
//                    getNewList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

//    /**
//     * 获取新闻列表
//     *
//     * @param pageNum
//     */
//    private void getNewList(int pageNum) {
//        if (pageNum == 1) {
//            currentPage = 1;
//        }
//        HashMap<String, Object> hashMap = new HashMap<>();
//        hashMap.put("curPage", pageNum);
//        hashMap.put("pageSize", Constant.PAGE_SIZE);
//        hashMap.put("contentType", id);
//        String str = GsonUtils.toJson(hashMap);
//        OkGo.<String>post(MyConstant.POST_NEWS_LIST)
//                .tag(this)
//                .upJson(str)
//                .execute(new StringDialogCallback(getActivity()) {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//                        String result = response.body();
//                        if (!StringUtils.isEmpty(result)) {
//
//                            try {
//                                Gson gson = GsonFactory.getSingletonGson();
//                                ExchangeMessageBean exchangeBean = new ExchangeMessageBean();
//                                exchangeBean = gson.fromJson(result, ExchangeMessageBean.class);
//                                List<ExchangeMessageBean.PageBean.ListBean> dataBeans = exchangeBean.getPage().getList();
//
//                                try {
//                                    emptyLayout.setIsShowView(false);
//                                    recycler.setVisibility(View.VISIBLE);
//
//                                    if (dataBeans != null) {
//
//                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
//                                        if (!isLoadMore) {
//                                            if (currentPage > 1) {
//                                                ToastUtils.showLong(getResources().getString(R.string.text_no_more_data));
//                                            } else {
//                                                if (dataBeans.size() == 0) {
//                                                    //显示占位图
//                                                    emptyLayout.setIsShowView(true);
//                                                    recycler.setVisibility(View.GONE);
//                                                }
//
//                                            }
//                                        }
//
//                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
//                                        if (currentPage == 1) {
//                                            fileAdapter.clearData();
//                                        }
//                                        DataBean.addAll(dataBeans);
//                                        fileAdapter.upData(DataBean);
//
//                                    } else {
//                                        if (currentPage == 1) {
//                                            //显示占位图
//                                            recycler.setVisibility(View.GONE);
//                                            emptyLayout.setIsShowView(true);
//                                        }
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//
//                            } catch (JsonSyntaxException e) {
//
//                                e.printStackTrace();
//                                isLoadMore = false;
//                                emptyLayout.setIsShowView(true);
//                                recycler.setVisibility(View.GONE);
//                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));
//
//                            }
//                        }
//
//                    }
//                });
//    }

    /**
     * 获取文件名称
     */
    private List<String> getFileInfo(File[] files) {
        // 先判断目录是否为空，否则会报空指针
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    getFileInfo(file.listFiles());
                } else {
                    //文件名称
                    String fileName = file.getName();
                    //文件路径 ： file.getPath()
                    if (fileName.endsWith(".pdf") || fileName.endsWith(".docx")) {
                        data.add(fileName);
                    }
                }
            }
            return data;
        }
        return null;
    }

}